package matt.design;

import java.text.ParseException;
import java.util.Scanner;

import com.google.android.maps.GeoPoint;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

public class EditTaskActivity extends Activity {
	static Item currentTask;
	private TextView sDisplay;
    private Button StartDate;
    private TextView dDisplay;
    private Button DueDate;
    private int sYear, dYear;
    private int sMonth, dMonth;
    private int sDay, dDay;
    static final int DATE_DIALOG_ID = 0;
    static final int DATE_DIALOG_ID2 = 1;
    private String group = "Default";
    private int priority = 0;
    private String recurring = "Once";
    private String location;
    private GeoPoint locPoint;
    private String latitude, longitude;
	
	/**
	 * Method that defines the actions to take place when the activity is first created
	 * 
	 * @param savedInstanceState
	 */
	public void onCreate(Bundle savedInstanceState) {
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_task);
		
		latitude = currentTask.getLatitude();
		longitude = currentTask.getLongitude();
		location = currentTask.getAddress();
		
		HomepageActivity.datasource = new TasksDataSource(this);
		HomepageActivity.datasource.open();
		
		final Button groupButton = (Button) findViewById(R.id.group);
		final Button priorityButton = (Button) findViewById(R.id.priority);
		final Button recurringButton = (Button) findViewById(R.id.recurring);
		final EditText taskNameText = (EditText) findViewById(R.id.taskName);
		final EditText description = (EditText) findViewById(R.id.description);
		final EditText location = (EditText) findViewById(R.id.location);
		Button addTask = (Button) findViewById(R.id.btn_add_task);
		
		final ImageButton mapsAction = (ImageButton) findViewById(R.id.btn_googlemaps);
		
		
		mapsAction.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				startActivityForResult(new Intent(getApplicationContext(), MapsActivity.class), 1);
			}
		});
		
		addTask.setText("Edit Task");
		taskNameText.setText(currentTask.getItemName());
		description.setText(currentTask.getDesc());
		groupButton.setText(currentTask.getItemGroup().getName());
		location.setText(currentTask.getAddress());
		latitude = currentTask.getLatitude();
		longitude = currentTask.getLongitude();
		if(currentTask.getAddress() == null)
			location.setText(" NULL ");
		else if(currentTask.getAddress().equals(""))
			location.setText(" NONE ");
		if(currentTask.getPriority() == 2){
			priorityButton.setText("Medium");
		}
		else if(currentTask.getPriority() == 3){
			priorityButton.setText("High");
		}
		
		recurringButton.setText(currentTask.getRecurring());
		
		Scanner Scan = new Scanner(currentTask.getDueDate());
    	Scan.useDelimiter("-");
    	dMonth = Scan.nextInt()-1;
    	dDay = Scan.nextInt();
    	dYear = Scan.nextInt();
    	Scanner Scan2 = new Scanner(currentTask.getStartDate());
    	Scan2.useDelimiter("-");
    	sMonth = Scan2.nextInt()-1;
    	sDay = Scan2.nextInt();
    	sYear = Scan2.nextInt();
		
		//Group's button listener
		final AlertDialog.Builder groupBuilder = new AlertDialog.Builder(this);
		groupButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				final String[] groups = {"Default", "Work", "School", "Personal"};
				groupBuilder.setTitle("Choose a Group");
				groupBuilder.setCancelable(false);
				groupBuilder.setSingleChoiceItems(groups, -1, new DialogInterface.OnClickListener(){
					public void onClick(DialogInterface dialog, int item){
						group = groups[item];
						groupButton.setText(groups[item]);
						dialog.dismiss();
					}
				});
				groupBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();						
					}
				});
				AlertDialog alert = groupBuilder.create();
				alert.show();
			}
		});
		
		final AlertDialog.Builder priorityBuilder = new AlertDialog.Builder(this);
		priorityButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				final String[] prio = {"Low", "Medium", "High"};
				priorityBuilder.setTitle("Set Priority");
				priorityBuilder.setCancelable(false);
				priorityBuilder.setSingleChoiceItems(prio, -1, new DialogInterface.OnClickListener(){
					public void onClick(DialogInterface dialog, int item){
						if(prio[item] == "Low"){
							priority = 1;
						}
						else if(prio[item] == "Medium"){
							priority = 2;
						}
						else if(prio[item] == "High"){
							priority = 3;
						}
						priorityButton.setText(prio[item]);
						dialog.dismiss();
					}
				});
				priorityBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();						
					}
				});
				AlertDialog alert = priorityBuilder.create();
				alert.show();
			}
		});
		
		final AlertDialog.Builder recurringBuilder = new AlertDialog.Builder(this);
		recurringButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				final String[] recur = {"Once", "Weekly", "Monthly", "Yearly"};
				recurringBuilder.setTitle("Set Priority");
				recurringBuilder.setCancelable(false);
				recurringBuilder.setSingleChoiceItems(recur, -1, new DialogInterface.OnClickListener(){
					public void onClick(DialogInterface dialog, int item){
						recurring = recur[item];
						recurringButton.setText(recur[item]);
						dialog.dismiss();
					}
				});
				recurringBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();						
					}
				});
				AlertDialog alert = recurringBuilder.create();
				alert.show();
			}
		});
		
		// capture our View elements and set values
        dDisplay = (TextView) findViewById(R.id.dueDate);
        DueDate = (Button) findViewById(R.id.dueDate);
        sDisplay = (TextView) findViewById(R.id.startDate);
        StartDate = (Button) findViewById(R.id.startDate);
        
       // add a click listener to the button
        DueDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });
        
        StartDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID2);
            }
        });
        

        
        //Set the dates to the desired dates
        DueDate.setText(currentTask.getDueDate());
        StartDate.setText(currentTask.getStartDate());
        
		
        //Already declared add
		Button cancel = (Button) findViewById(R.id.btn_cancel);
		
		addTask.setOnClickListener(new View.OnClickListener() {

			EditText taskNameText = (EditText) findViewById(R.id.taskName);
			EditText descText = (EditText) findViewById(R.id.description);
			
			/**
			 * Determines what happens when the login button is clicked
			 * 
			 * @param v
			 */
			public void onClick(View v) {
				
				Item item = null;
				String taskName = taskNameText.getText().toString();
				String desc = descText.getText().toString();
				
								
				if (taskName.equals("")) {
					TextView error = (TextView) findViewById(R.id.btn_add_task_errormsg);
					error.setText("Please input a name");
				}
				else {
								
					//Sets the dates based on selected date
//					String dueDate =((Integer)(dMonth+1)).toString() +"-" +  ((Integer) dDay).toString()+"-"+ ((Integer) dYear).toString();
//					String startDate =((Integer)(sMonth+1)).toString() + "-" +((Integer) sDay).toString()+"-"+ ((Integer) sYear).toString();
//					String dueDate = DueDate.getText().toString();
//					String startDate = StartDate.getText().toString();
					
//					try {
//						item = HomepageActivity.datasource.updateTask(taskName, desc, dueDate, startDate, 
//								priority, group, recurring, false);
//					} catch (ParseException e) {
//						e.printStackTrace();
//					}
					
					currentTask.setItemName(taskName);
					currentTask.setDesc(desc);
					currentTask.setDueDate(DueDate.getText().toString());
					currentTask.setStartDate(StartDate.getText().toString());
					currentTask.setItemGroup(new Group(groupButton.getText().toString()));
					currentTask.setAddress(location.getText().toString());
					currentTask.setLatitude(latitude);
					currentTask.setLongitude(longitude);
					if(priorityButton.getText().toString().equals("Low")){
						currentTask.setPriority(1);
					}
					else if(priorityButton.getText().toString().equals("Medium")){
						currentTask.setPriority(2);
					}
					else{
						currentTask.setPriority(3);
					}
					if(recurringButton.getText().equals("Once")){
						currentTask.setRecurring("Once");
					}
					else if(recurringButton.getText().equals("Weekly")){
						currentTask.setRecurring("Weekly");
					}
					else if(recurringButton.getText().equals("Monthly")){
						currentTask.setRecurring("Monthly");
					}
					else{
						currentTask.setRecurring("Yearly");
					}
					
					HomepageActivity.datasource.updateTask(currentTask);
					
					finish();
				}
			}
		});
		
		cancel.setOnClickListener(new View.OnClickListener() {
			
			EditText taskNameText = (EditText) findViewById(R.id.taskName);
			EditText descText = (EditText) findViewById(R.id.description);
			Button groupButton = (Button) findViewById(R.id.group);
			Button priorityButton = (Button) findViewById(R.id.priority);
			Button recurringButton = (Button) findViewById(R.id.recurring);
			TextView error = (TextView) findViewById(R.id.btn_add_task_errormsg);
			
			public void onClick(View v) {
				taskNameText.setText("");
				descText.setText("");
				error.setText("");
				groupButton.setText("---");
				priorityButton.setText("Low");
				recurringButton.setText("Once");
				
				finish();
			}
		});
	}
	
	@Override
	protected void onResume() {
		HomepageActivity.datasource.open();
		super.onResume();
	}

	@Override
	protected void onPause() {
		HomepageActivity.datasource.close();
		super.onPause();
	}
	
	private void updateDisplay(TextView display ,int month, int day, int year) {
        display.setText(((Integer)(month+1)).toString() +"-" +((Integer) day).toString()+"-"+ ((Integer)year).toString());
    }
	
	protected Dialog onCreateDialog(int id) {
	    switch (id) {
	    case DATE_DIALOG_ID:
	        return new DatePickerDialog(this, DueDateSetListener, dYear, dMonth, dDay);
	 
	    case DATE_DIALOG_ID2:
	    	return new DatePickerDialog(this, StartDateSetListener, sYear, sMonth, sDay);
	    }
	    return null;
	}
	
	private DatePickerDialog.OnDateSetListener DueDateSetListener = new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    dYear = year;
                    dMonth = monthOfYear;
                    dDay = dayOfMonth;
                    updateDisplay(DueDate, dMonth, dDay, dYear);
                    
                }
            };
            
     private DatePickerDialog.OnDateSetListener StartDateSetListener = new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    sYear = year;
                    sMonth = monthOfYear;
                    sDay = dayOfMonth;
                    updateDisplay(StartDate, sMonth, sDay, sYear);
                }
            };
            
     protected void onActivityResult(int requestCode, int resultCode, Intent data){
    	 EditText where = (EditText) findViewById(R.id.location);
    	 if(resultCode != 0){
    		 System.out.print("Old/New lat: " + latitude);
	       	 latitude = data.getStringExtra("Lat");
	       	 System.out.print(": " + latitude + " Old/New long: " + longitude);
	       	 longitude = data.getStringExtra("Long");
	       	System.out.print(": " + longitude + " Old/New Addr: " + location);
	       	 location = data.getStringExtra("Address");
	       	System.out.print(": " + location);
	       	 if(latitude != null && longitude != null)
	       		 locPoint = new GeoPoint(Integer.parseInt(latitude), Integer.parseInt(longitude));
	       	 System.out.println("LOCATION " +locPoint);
	       	 where.setText(location);
    	 }
    	            	 
      }
}
